#include "stdafx.h"
#include "scenerenderer.h"
#include "model/mage.h"
#include "model/potion.h"
#include "model/spell.h"

namespace {

const float BAR_WIDTH = 48.0f;
const float BAR_HEIGHT = 5.0f;
const float BAR_DEPTH = 0.5f;
static float HEALTH_BAR_COLOR[4] = {1, 0, 0, 1};
static float MANA_BAR_COLOR[4] = {0, 0, 1, 1};

void drawStatsBar(float x, float y, bool isManaBar, float fraction)
{
    glColor4fv(isManaBar ? MANA_BAR_COLOR : HEALTH_BAR_COLOR);

    x = x - 0.5f * BAR_WIDTH;
    glBegin(GL_QUADS);
    {
        glVertex3f(x , y - 0.5f * BAR_HEIGHT, BAR_DEPTH - 1e-3);
        glVertex3f(x + fraction * BAR_WIDTH, y - 0.5f * BAR_HEIGHT, BAR_DEPTH - 1e-3);
        glVertex3f(x + fraction * BAR_WIDTH, y + 0.5f * BAR_HEIGHT, BAR_DEPTH - 1e-3);
        glVertex3f(x, y + 0.5f * BAR_HEIGHT, BAR_DEPTH - 1e-3);
    }
    glEnd();
}

}

SceneRenderer::SceneRenderer()
{
}

SceneRenderer::~SceneRenderer()
{
}

void SceneRenderer::init()
{
    _pool.init();
}

void SceneRenderer::visit(Mage *mage)
{
    //! FIXME: it's dirty work around!
    glPushMatrix();
    glTranslatef(mage->x(), mage->y(), 0);
    glRotatef(90.0f - 180.f / 3.14f * mage->direction(), 0, 0, 1);
    _pool.mage(SpritesPool::Color_Blue).render(0, 0);
    glPopMatrix();

    float healthFract = static_cast<float>(mage->health()) / Mage::MAX_HEALTH;
    float manaFract = static_cast<float>(mage->mana()) / Mage::MAX_MANA;
    drawStatsBar(mage->x(), mage->y() - 36, false, healthFract);
    drawStatsBar(mage->x(), mage->y() - 29, true, manaFract);
}

void SceneRenderer::visit(Potion *potion)
{
    if (potion->kind() == Potion::MANA_POTION)
        _pool.manaPotion(SpritesPool::Size_Small).render(potion->x(), potion->y());
    else
        _pool.healthPotion(SpritesPool::Size_Small).render(potion->x(), potion->y());
}

void SceneRenderer::visit(Spell *spell)
{
    SpritesPool::Spell index;
    switch (spell->kind())
    {
        case Spell::FIREBALL:
            index = SpritesPool::Spell_Fireball;
            break;
        case Spell::FROSTBALL:
            index = SpritesPool::Spell_Frostball;
            break;
        case Spell::MAGIC_ARROW:
        default:
            index = SpritesPool::Spell_MagicArrow;
            break;
    }

    _pool.spell(index).render(spell->x(), spell->y());
}
